
import * as React from 'react'
import { NavBar, Icon, FlatList } from 'components'
import moment from 'moment'
import { formatPriceStr } from '../../methods'
import * as echarts from 'echarts'
import 'hidpi-canvas/dist/hidpi-canvas.min.js'
import { post, NotBean } from '../../../../utils'
import './ExChangeStatistics.less'

export default class ExChangeStatistics extends React.Component<any, any> {

    public canvasPie: any
    public canvasLine: any
    public parentRef: any
    public state = {
        echartType: 'circle',
        canvasData: [
            {
                color: '#fa0000',
                value: '0'
            },
            {
                color: '#fa0000',
                value: '96'
            }
        ],
        width: 0,
        height: 0,
        wid: {
            l1: 4,
            l2: 10
        },
        time: {
            stime: moment().subtract(1, 'y').toDate(),
            etime: moment().toDate(),
        },
        lineData: [],
    }
    public node: any
    public index: number = 1
    public componentDidMount () {
        this.getData()
    }

    public render(): JSX.Element {
        const { echartType, height, width} = this.state
        const { userCreditor, userHypoExchangeList } = this.props
        console.log(this.props)
        return (
            <div className="exChangeStatistics">
                <NavBar
                    title={<div style={{fontSize: '0.97rem', color: '#222'}}>兑换统计</div>}
                    fixed={true}
                />
                <div className="exChangeStatistics_contentWrap">
                    <div className="exChangeStatistics_topBg" />
                    <div className="exChangeStatistics_content">
                        <div className="exChangeStatistics_content_top">
                            <div>
                                <img className="exChangeStatistics_content_top_img" src={require('../../../../assets/statistics_titlebg0.png')} />
                                <div className="exChangeStatistics_content_top_toggle">
                                    <span 
                                        onClick={() => {this.handleToggleType('circle')}}
                                        className={`${(echartType === 'circle') ? 'exChangeStatistics_content_top_toggle_active' : ''}`}
                                    ><Icon type="statistics" />
                                    </span>
                                    <span
                                        onClick={() => {this.handleToggleType('line')}} 
                                        className={`${(echartType === 'line') ? 'exChangeStatistics_content_top_toggle_active' : ''}`}
                                    ><Icon type="statistics_line" />
                                    </span>
                                </div>
                            </div>
                            <div className="exChangeStatistics_content_top_value">{userCreditor.surplus_price && formatPriceStr(userCreditor.surplus_price.toString())}</div>
                        </div>
                        <div className="exChangeStatistics_line">
                            <img src={require('../../../../assets/category_item_bgLine.png')} />
                        </div>
                        <div className="exChangeStatistics_echart" ref={(ref) => {this.parentRef = ref}}>
                            {
                                (echartType === 'circle') 
                                ? (width && height) 
                                    ? <React.Fragment>
                                        <canvas height={height} width={width} ref={(ref) => {this.canvasPie = ref}} />
                                    <div className="exChangeStatistics_echart_text">
                                        <div>
                                            <div>总债务数</div>
                                            <div className="DINPro">{userCreditor.arrears_price}</div>
                                        </div>
                                    </div>
                                    </React.Fragment>
                                    : '' 
                                : ''
                            }
                            {
                                (width && height && echartType === 'line') 
                                ? <canvas height={height} width={width} ref={(ref) => {this.canvasLine = ref}} />
                                : ''
                            }
                            
                        </div>
                        <div className="exChangeStatistics_dotted">
                            <img src={require('../../../../assets/category_item_bgDotte.png')} />
                        </div>
                        <div className="exChangeStatistics_record_title">
                            <img src={require('../../../../assets/statistics_titlebg1.png')} />
                        </div>
                        <div className="exChangeStatistics_recordList_item exChangeStatistics_recordList_tablehead">
                            <div>债务人</div>
                            <div>领取数量</div>
                            <div>领取时间</div>
                        </div>
                        <FlatList 
                            ref={(ref) => {this.node = ref}}
                            data={userHypoExchangeList}
                            onRefresh={this.getRecodeData} 
                            ListEmptyComponent={NotBean}
                            renderItem={(item: any, index: number) => {
                                return (
                                    <div className="exChangeStatistics_recordList_item" key={index}>
                                        <div>{item.shop_zw_users.real_name}</div>
                                        <div>{formatPriceStr(item.price.toString())}</div>
                                        <div>{moment(item.create_time).format('YYYY-MM-DD HH:mm')}</div>
                                    </div>
                                )
                            }}
                        />
                    </div>
                </div>
            </div>
        )
    }
    private getData = () => {
        const { userInfo, SET_MYUTILS_CREDITOR } = this.props
        post('usersapi/userZqManage', {
            userId: userInfo.id
        }).then((data: any) => {
            console.log(data)
            SET_MYUTILS_CREDITOR(data)
            const wid = this.handleLabelLineWid(data.sum_price, data.residue_q)
            this.setState({height: this.parentRef.clientHeight, width: this.parentRef.clientWidth, wid: wid}, this.initCanvasPie)
        })
    }
    private getRecodeData = () => {
        const { time } = this.state
        const { userInfo, SET_MYUTILS_HYPOEXCHANGELIST, userHypoExchangeList } = this.props
        post('usersapi/userZqDrawLog', {
            page: this.index,
            userId: userInfo.id,
            stime: moment(time.stime).format('YYYY-MM-DD'),
            etime: moment(time.etime).format('YYYY-MM-DD'),
        }).then((data: any) => {
            console.log(userHypoExchangeList)
            if (this.index === 1) {
                SET_MYUTILS_HYPOEXCHANGELIST(data.data)
            }  else {
                if (data.data.length) {
                    SET_MYUTILS_HYPOEXCHANGELIST(userHypoExchangeList.concat(data.data))
                    this.node.finishLoad()
                }
            }
            this.index++
        })
        
    }
    private getPieData = () => {
        const { userCreditor } = this.props
        return [
            {value: userCreditor.arrears_price - userCreditor.surplus_price, name: '已领取'},
            {value: userCreditor.surplus_price, name: '未领取'},
        ]
    }
    private handleToggleType = (val: string) => {
        console.log(val)
        let fun: any
        if (val === 'circle') {
            fun = this.initCanvasPie
            this.setState({echartType: val}, fun)
        }
        if (val === 'line') {
            const { userInfo } = this.props
            post('usersapi/userBeanLogZqCount', {
                userId: userInfo.id,
                stime: moment().subtract(4, 'months').format('YYYY-MM-DD'),
                etime: moment().format('YYYY-MM-DD'),
            }).then((data: any) => {
                fun = this.initCanvasLine
                let t = data.map((item: any) => {
                    return item.sum
                })
                this.setState({echartType: val, lineData: t}, fun)
            })
        }
    }
    private initCanvasPie = () => {
        let lineWid = this.state.wid
        echarts.init(this.canvasPie).setOption({
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            grid: {
                x: 35,
                y: 55,
                x2: 35,
                y2: 60,
                borderWidth: 1 
            },
            color: ['#00c5b7', '#ff862d'],
            animation: false,
            series: [
                {
                    name: '恒豆领取',
                    type: 'pie',
                    radius: ['28%', '53%'],
                    avoidLabelOverlap: false,
                    label: {
                        normal: {
                            formatter: '{c}\n{b}',
                            show: true,
                            position: 'outside'
                        },
                    },
                    labelLine: {
                        show: true,
                        length: lineWid.l1,
                        length2: lineWid.l2
                    },
                    data: this.getPieData()
                }
            ]
        })
    }
    private initCanvasLine = () => {
        const option1 = {
            grid: {
                x: 10,
                y: 55,
                x2: 10,
                y2: 60,
                borderWidth: 1 
            },
            
            xAxis:  {
                type: 'category',
                // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
            },
            yAxis: {
                type: 'value',
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                splitLine: {
                    show: false
                },
                axisLabel : {
                    formatter: function () {
                          return ''
                    }
                }
            },
            series: [
                {
                    symbol: 'image://' + require('../../../../assets/echart_symbol.png'),
                    name: '用电量',
                    type: 'line',
                    smooth: false,
                    data: this.state.lineData,
                    itemStyle : {
                            normal : {
                            color: '#ff862d',
                            label: {
                                show: true
                            },
                        }
                    },
                    label: {
                        normal: {
                            show: true,
                            position: 'top',
                            textStyle: {
                                color: '#999999',
                                fontSize: '12.5',
                            }
                        }
                    }
                }
            ]
        }
        echarts.init(this.canvasLine).setOption(option1)
    }
    private handleLabelLineWid = (received: any, unReceived: any) => {
        const all: any = parseInt(received, 10) + parseInt(unReceived, 10)
        const re = received / all
        console.log(re)
        if (re > 0 && re < 0.25) {
            console.log(1)
            return {
                l1: 12,
                l2: 60
            }
        } else if (re >= 0.25 && re < 0.5) {
            console.log(2)
            return {
                l1: 8,
                l2: 40
            }
        } else if (re >= 0.5 && re < 0.75) {
            console.log(3)
            return {
                l1: 4,
                l2: 20
            }
        } else if (re >= 0.75 && re < 1) {
            console.log(4)
            return {
                l1: 12,
                l2: 60
            }
        } else {
            console.log(5)
            return {
                l1: 12,
                l2: 60
            }
        }
    }
    // private goToUrl = (url: string = '/') => {
    //     this.props.history.push(url)
    // }
}